<template>
  <div class="profile-page page-container">
    <!-- 顶部导航 -->
    <van-nav-bar title="个人资料" left-arrow @click-left="router.back()" />

    <div class="content-container content-container">
      <!-- 加载状态 -->
      <van-overlay :show="loading" class="loading-overlay">
        <van-loading type="spinner" color="#4080ff" />
      </van-overlay>

      <!-- 头像上传 -->
      <div class="avatar-card">
        <div class="avatar-title">个人头像</div>
        <div class="avatar-upload">
          <van-uploader v-model="profileForm.avatarFile" :max-count="1" :after-read="afterAvatarRead"
            :before-delete="beforeAvatarDelete" accept="image/*" :preview-size="100" :preview-image="false">
            <div class="avatar-preview">
              <img :src="profileForm.avatar" alt="头像" @error="handleImageError" />
              <div class="upload-mask">
                <van-icon name="edit" size="24" />
                <span>编辑头像</span>
              </div>
            </div>
          </van-uploader>
        </div>
      </div>

      <!-- 表单内容 -->
      <div class="form-card">
        <van-cell-group>
          <van-field v-model="profileForm.username" label="用户名" placeholder="请输入用户名" :readonly="!canChangeUsername"
            input-align="right" class="form-field" />

          <van-field v-model="profileForm.nickname" label="昵称" placeholder="请输入昵称" input-align="right"
            class="form-field" :rules="[{ required: true, message: '请输入昵称' }]" />

          <van-field v-model="profileForm.email" label="邮箱" placeholder="请输入邮箱" type="email" input-align="right"
            class="form-field" />

          <!-- 使用 Field 组件模拟 Cell -->
          <van-field v-model="genderText" label="性别" readonly is-link input-align="right" class="form-field"
            @click="showGenderPicker = true" />
        </van-cell-group>
      </div>

      <!-- 个人简介 -->
      <div class="bio-card">
        <div class="bio-title">个人简介</div>
        <van-field v-model="profileForm.bio" type="textarea" placeholder="介绍一下自己吧" rows="3" autosize maxlength="200"
          show-word-limit class="bio-textarea" />
      </div>

      <!-- 操作按钮区域 -->
      <div class="action-buttons">
        <!-- 保存按钮 -->
        <van-button block type="primary" class="save-btn" @click="handleSaveProfile" :loading="saving">
          {{ saving ? '保存中...' : '保存个人资料' }}
        </van-button>

        <!-- 修改密码按钮 -->
        <van-button block type="default" class="change-password-btn" @click="goToChangePassword">
          修改密码
        </van-button>
      </div>

      <!-- 性别选择器弹窗 -->
      <van-popup v-model:show="showGenderPicker" position="bottom">
        <van-picker :columns="genderOptions" @confirm="onGenderConfirm" @cancel="showGenderPicker = false" show-toolbar
          title="选择性别" />
      </van-popup>

      <!-- 简化的图片裁剪弹窗 -->
      <van-dialog v-model:show="showCropper" title="裁剪头像" :show-confirm-button="!uploading"
        :show-cancel-button="!uploading" @confirm="confirmCrop" close-on-click-overlay
        :before-close="handleCropperClose" class="cropper-dialog">
        <div class="cropper-container">
          <vue-cropper ref="cropperRef" :img="cropperImage" :outputSize="1" :outputType="'png'" :info="true"
            :full="false" :can-move="true" :can-move-box="true" :original="false" :autoCrop="true" :autoCropWidth="200"
            :autoCropHeight="200" :fixedBox="false" :fixed="true" :fixedNumber="[1, 1]" :centerBox="true" :high="true"
            :infoTrue="true"></vue-cropper>
        </div>
        <div class="cropper-tip">
          <van-icon name="info-o" />
          <span>拖动图片并调整裁剪框大小</span>
        </div>
        <div v-if="uploading" class="uploading-overlay">
          <van-loading type="spinner" color="#4080ff" size="24px" />
          <span class="uploading-text">上传中...</span>
        </div>
      </van-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { showToast, showDialog } from 'vant';
import { useUserStore } from '@/stores/user';
import { userApi } from '@/api/user';
import { getImageUrl, handleImageError } from '@/utils/image';
// 使用 vue-cropper 替代 vue-advanced-cropper
import 'vue-cropper/dist/index.css';
import { VueCropper } from 'vue-cropper';

const router = useRouter();
const userStore = useUserStore();

// 默认头像
const defaultAvatar = 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg';

// 用户信息
const userInfo = computed(() => userStore.userInfo);
const isLoggedIn = computed(() => userStore.isLoggedIn);

// 是否可以修改用户名 - 改为可修改
const canChangeUsername = ref(true);

// 加载状态
const loading = ref(true);
const saving = ref(false);
const uploading = ref(false);

// 性别选择器
const showGenderPicker = ref(false);

// 性别选项
const genderOptions = [
  { text: '男', value: 1 },
  { text: '女', value: 2 }
];

// 性别显示文本
const genderText = computed(() => {
  if (profileForm.value.gender === 1) return '男';
  if (profileForm.value.gender === 2) return '女';
  return '未知';

});

// 性别选择确认
const onGenderConfirm = (value) => {
  profileForm.value.gender = value.selectedOptions[0].value || 0;
  showGenderPicker.value = false;
};

// 图片裁剪相关
const showCropper = ref(false);
const cropperRef = ref(null);
const cropperImage = ref('');

// 个人资料表单
const profileForm = ref({
  username: '',
  nickname: '',
  email: '',
  bio: '',
  avatar: '',
  avatarFile: [] as any[],
  gender: 0,
  birthday: ''
});

// 初始化表单数据
const initProfileForm = () => {
  profileForm.value = {
    username: userInfo.value?.username || '',
    nickname: userInfo.value?.nickname || '',
    email: userInfo.value?.email || '',
    bio: userInfo.value?.bio || '',
    avatar: userInfo.value?.avatar || '',
    avatarFile: [],
    gender: userInfo.value?.gender || 0,
    birthday: userInfo.value?.birthday || ''
  };
};

// 监听用户信息变化，更新表单数据
watch(() => userInfo.value, (newVal) => {
  if (newVal) {
    initProfileForm();
  }
}, { immediate: true });

// 页面加载时获取数据
onMounted(async () => {
  try {
    // 检查登录状态
    if (!isLoggedIn.value) {
      router.push('/auth/login');
      return;
    }
    // 初始化表单数据
    initProfileForm();
  } catch (error) {
    console.error('初始化数据失败:', error);
    showToast('获取用户信息失败，请重试');
  } finally {
    loading.value = false;
  }
});

// 头像上传后的处理
const afterAvatarRead = async (file: any) => {
  // 检查文件类型
  if (!file.file.type.includes('image/')) {
    showToast('请选择图片文件');
    profileForm.value.avatarFile = [];
    return;
  }

  // 检查文件大小（限制为2MB）
  if (file.file.size > 2 * 1024 * 1024) {
    showToast('图片大小不能超过2MB');
    profileForm.value.avatarFile = [];
    return;
  }

  // 读取文件为 base64
  const reader = new FileReader();
  reader.onload = (e) => {
    cropperImage.value = e.target?.result as string;
    showCropper.value = true;
  };
  reader.readAsDataURL(file.file);

  // 清空上传队列，等待裁剪后再上传
  profileForm.value.avatarFile = [];
};

// 确认裁剪
const confirmCrop = async () => {
  if (!cropperRef.value || uploading.value) return;

  uploading.value = true;

  try {
    // 获取裁剪后的图片数据 (base64)
    cropperRef.value.getCropBlob((blob) => {
      if (!blob) {
        showToast('裁剪失败，请重试');
        uploading.value = false;
        return;
      }

      // 创建 FormData 对象
      const formData = new FormData();
      formData.append('file', blob, 'avatar.png');

      // 上传头像
      userApi.uploadAvatar(formData)
        .then(response => {
          if (response?.url) {
            // 更新头像 URL
            profileForm.value.avatar = response.url;
            showToast('头像上传成功');

            // 更新用户信息中的头像
            if (userInfo.value) {
              userStore.userInfo = {
                ...userInfo.value,
                avatar: response.url
              };
            }
          } else {
            showToast('头像上传失败');
          }
        })
        .catch(error => {
          console.error('上传头像失败:', error);
          showToast('上传头像失败，请重试');
        })
        .finally(() => {
          uploading.value = false;
          showCropper.value = false;
        });
    });
  } catch (error) {
    console.error('裁剪头像失败:', error);
    showToast('裁剪失败，请重试');
    uploading.value = false;
  }
};

// 关闭裁剪弹窗前的处理
const handleCropperClose = (action: string, done: () => void) => {
  if (uploading.value) {
    // 如果正在上传，阻止关闭
    return false;
  }
  done();
  return true;
};

// 跳转到修改密码页面
const goToChangePassword = () => {
  router.push('/user/change-password');
};

// 保存个人资料
const handleSaveProfile = async () => {
  if (!isLoggedIn.value) {
    showToast('请先登录');
    return;
  }

  if (!profileForm.value.nickname.trim()) {
    showToast('昵称不能为空');
    return;
  }

  if (canChangeUsername.value && !profileForm.value.username.trim()) {
    showToast('用户名不能为空');
    return;
  }

  saving.value = true;

  // 显示保存中提示
  const toast = showToast({
    type: 'loading',
    message: '保存中...',
    duration: 0
  });

  try {
    // 构建更新数据
    const updateData: any = {
      nickname: profileForm.value.nickname,
      bio: profileForm.value.bio,
      email: profileForm.value.email,
      gender: profileForm.value.gender
    };

    // 处理生日字段
    if (profileForm.value.birthday) {
      // 确保生日是 ISO 格式的字符串
      updateData.birthday = new Date(profileForm.value.birthday).toISOString().split('T')[0];
    }

    // 如果可以修改用户名且有变更
    if (canChangeUsername.value && profileForm.value.username !== userInfo.value?.username) {
      updateData.username = profileForm.value.username;
    }

    // 调用更新API
    await userApi.updateUserInfo(updateData);

    // 关闭保存中提示
    toast.close();

    // 更新本地用户信息
    await userStore.getUserInfo(true);

    showToast('个人资料更新成功');

    // 延迟返回，让用户看到成功提示
    setTimeout(() => {
      router.back();
    }, 1000);
  } catch (error: any) {
    console.error('更新个人资料失败:', error);
    showToast(error.response?.data?.message || error.message || '更新失败，请重试');
  } finally {
    saving.value = false;
    toast.close();
  }
};

// 删除头像前的处理
const beforeAvatarDelete = () => {
  // 重置为原头像
  profileForm.value.avatar = userInfo.value?.avatar || '';
  return true;
};
</script>

<style scoped lang="scss">
.profile-page {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.content-container {
  padding: 16px;
  padding-bottom: 32px;
}

.loading-overlay {
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-card,
.form-card,
.bio-card {
  background-color: #fff;
  border-radius: 12px;
  margin-bottom: 16px;
  padding: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.avatar-title,
.bio-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  color: #333;
}

.avatar-upload {
  display: flex;
  justify-content: center;
}

.avatar-preview {
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .upload-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #fff;
    opacity: 0.9;
    /* 修改为始终显示 */
    transition: opacity 0.3s;

    span {
      font-size: 12px;
      margin-top: 4px;
    }
  }
}

.form-field {
  padding: 12px 0;
}

.bio-textarea {
  margin-top: 8px;

  :deep(.van-field__control) {
    min-height: 80px;
    padding: 8px;
    background-color: #f7f8fa;
    border-radius: 8px;
  }
}

.action-buttons {
  margin-top: 24px;
  display: flex;
  flex-direction: column;
  gap: 16px;

  .save-btn,
  .change-password-btn {
    height: 44px;
    border-radius: 8px;
    font-size: 16px;
    font-weight: 500;
  }

  .save-btn {
    background: linear-gradient(135deg, #4080ff, #5e96ff);
    border: none;
    box-shadow: 0 4px 12px rgba(64, 128, 255, 0.3);
  }

  .change-password-btn {
    color: #4080ff;
    background-color: rgba(64, 128, 255, 0.1);
    border: 1px solid rgba(64, 128, 255, 0.2);
  }
}

.cropper-container {
  height: 350px;
  width: 100%;
  background-color: #000;
  overflow: hidden;
}

.cropper-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  background-color: #f7f8fa;
  color: #666;
  font-size: 14px;

  .van-icon {
    margin-right: 5px;
    color: #4080ff;
  }
}

.uploading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 10;

  .uploading-text {
    margin-top: 12px;
    color: #fff;
    font-size: 14px;
  }
}

/* 确保裁剪对话框样式正确 */
:deep(.cropper-dialog) {
  .van-dialog__content {
    padding: 0;
  }
}
</style>
